document.addEventListener('DOMContentLoaded', () => {
    let grid = [];
    let score = 0;
    let bestScore = localStorage.getItem('bestScore') || 0;
    const gridSize = 4;
    let touchStartX = 0;
    let touchStartY = 0;
    let sessionId = INIT_SESSION_ID || generateSessionId();
    let timeLeft = 300; // 5分钟倒计时
    let timerInterval;

    function generateSessionId() {
        const id = Math.random().toString(36).substring(2) + Date.now().toString(36);
        localStorage.setItem('sessionId', id);
        return id;
    }

    function startTimer() {
        if (timerInterval) {
            clearInterval(timerInterval);
        }
        timerInterval = setInterval(() => {
            // 不在前端自行计时，而是依赖后端返回的时间
            const currentTime = document.getElementById('timer').textContent;
            if (currentTime === '0:00') {
                clearInterval(timerInterval);
                alert('时间到！游戏结束！最终得分：' + score);
                initGame();
            }
        }, 1000);
    }

    // 更新最高分
    function updateBestScore() {
        if (score > bestScore) {
            bestScore = score;
            localStorage.setItem('bestScore', bestScore);
        }
        document.getElementById('best-score').textContent = bestScore;
    }

    // 更新游戏状态
    function updateGameState(state) {
        grid = state.grid;
        score = state.score;
        updateScore();
        renderGrid();
        
        // 更新剩余时间显示
        if (state.remaining_time !== undefined) {
            const minutes = Math.floor(state.remaining_time / 60);
            const seconds = state.remaining_time % 60;
            document.getElementById('timer').textContent = 
                `${minutes}:${seconds.toString().padStart(2, '0')}`;
            
            if (state.remaining_time <= 0) {
                clearInterval(timerInterval);
                alert('时间到！游戏结束！最终得分：' + score);
                initGame();
            }
        }
        
        if (state.game_over) {
            clearInterval(timerInterval);
            alert('游戏结束！最终得分：' + score);
        }
    }

    // 初始化游戏
    async function initGame() {
        try {
            const timeLimit = parseInt(prompt('请输入游戏时间限制（秒），输入0表示无限制：', '300')) || 0;
            const response = await fetch(API_ENDPOINTS.new_game, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    session_id: sessionId,
                    time_limit: timeLimit
                })
            });
            const state = await response.json();
            if (state.error) {
                throw new Error(state.error);
            }
            updateGameState(state);
            startTimer(); // 开始计时
        } catch (error) {
            console.error('初始化游戏失败:', error);
            alert('初始化游戏失败，请刷新页面重试');
        }
    }

    // 更新分数
    function updateScore() {
        document.getElementById('score').textContent = score;
        updateBestScore();
    }

    // 渲染网格
    function renderGrid() {
        const gridElement = document.getElementById('grid');
        gridElement.innerHTML = '';
        for (let i = 0; i < gridSize; i++) {
            for (let j = 0; j < gridSize; j++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                const value = grid[i][j];
                if (value !== 0) {
                    cell.textContent = value;
                    cell.setAttribute('data-value', value);
                }
                gridElement.appendChild(cell);
            }
        }
    }

    // 移动处理
    async function move(direction) {
        const directionMap = {
            'ArrowUp': 'up',
            'ArrowRight': 'right',
            'ArrowDown': 'down',
            'ArrowLeft': 'left'
        };

        const response = await fetch(API_ENDPOINTS.move, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_id: sessionId,
                direction: directionMap[direction]
            })
        });

        const state = await response.json();
        if (!response.ok) {
            console.error('移动失败:', state.error);
            return;
        }
        updateGameState(state);
    }

    // 监听键盘事件
    document.addEventListener('keydown', (event) => {
        if (event.key === 'ArrowUp' || event.key === 'ArrowDown' || 
            event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
            event.preventDefault();
            move(event.key);
        }
    });

    // 添加触摸事件支持
    document.getElementById('grid').addEventListener('touchstart', (event) => {
        touchStartX = event.touches[0].clientX;
        touchStartY = event.touches[0].clientY;
        event.preventDefault();
    }, { passive: false });

    document.getElementById('grid').addEventListener('touchend', (event) => {
        const touchEndX = event.changedTouches[0].clientX;
        const touchEndY = event.changedTouches[0].clientY;
        
        const dx = touchEndX - touchStartX;
        const dy = touchEndY - touchStartY;
        event.preventDefault();

        // 根据滑动方向确定移动方向
        if (Math.abs(dx) > Math.abs(dy)) {
            if (dx > 0) {
                move('ArrowRight');
            } else {
                move('ArrowLeft');
            }
        } else {
            if (dy > 0) {
                move('ArrowDown');
            } else {
                move('ArrowUp');
            }
        }
    }, { passive: false });

    // 初始化游戏
    initGame();

    // 新游戏按钮事件监听
    document.getElementById('new-game').addEventListener('click', initGame);
});